// pages/takeOrders/takeOrders/takeOrders.js
var app =getApp();
var _PAGE = 1;
var _PAGESIZE = 10;
var timer;
var flowDoor = app.globalData._network_path + 'flowDoor.jpg';
let latitude = '', longitude = '', load = true, workid = '', distance = '',time='';
    //经纬度,       加载数据,                     选择的工单,   距离排序      时间排序

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isActive: 2,//抢单、指派切换
    screenTypes:[],//订单类型列表
    selectTypeid: [],//选中的订单类型ID
    selectType: '',//订单类型名
    screenShow: false,//订单类型模块显隐 
    isMaskShow: false,//遮罩层显隐
    isOrderSureShow: false,//确认抢单
    orderData: [],//订单数据
    orderNextData:[],
    isSortTime: 0,//时间排序
    isSortDis: 0,//距离排序
    empty: true,
    hasMore: false,
    loading: false,
    loadShow: false,
    isLocation: false,
    showFlag: false,
    move: 0,
    flowDoor: flowDoor,//广告图

    searchKey: '', //搜索关键字
    ordertypeList: [], //订单类型列表
    // ordertypeIndex: [], //筛选选中的订单类型
    distanceList: [], //距离列表
    selectDistance: '', //选中的距离
    move1: 0,//筛选弹窗
    screenShow1: false,//筛选模块显隐,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  
  onLoad: function (options) {
    
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if(wx.getStorageSync('token') != '' && wx.canIUse('getPrivacySetting')){
      wx.getPrivacySetting({
        success: (res) => {
          if (res.needAuthorization) wx.requirePrivacyAuthorize()
        }
      })
    }
	},
	handleDisagree() {
    wx.setStorageSync('token', '');
    wx.setStorageSync('openid', '');
		wx.navigateTo({
			url: '/pages/myCenter/login/login',
		})
	},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {  
    console.log(9999);
    var that = this;
    app.loginStatus(function () {
    }, function () {
    })
    load = true;
    _PAGE = 1;
    time = '';
    that.setData({
      isActive: 2,
      selectTypeid: [],
      selectType: '',
      screenShow: false, 
      isMaskShow: false,
      isOrderSureShow: false,
      isSortTime: 0,
      isSortDis: 0,
      orderData:[],      
    });
    var Type = that.data.isActive;  
    console.log(Type)
    that.getData(Type);
    // wx.getSetting({
    //   success: (res) => {
    //     // console.log(res);
    //     // console.log(res.authSetting['scope.userLocation']);
    //     if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
    //       console.log('1111******');
    //       //非初始化进入该页面,且未授权
    //       that.setData({
    //         isLoacation: false,
    //         showFlag: true
    //       })
    //     } else if (res.authSetting['scope.userLocation'] == undefined) {
    //       //初始化进入
    //       console.log('2222*****');
    //       that.getLocation(function () {
    //         that.getData(Type)
    //       });
    //     }else{
    //       console.log('3333*****');          
    //       that.getLocation(function () {
    //         that.getData(Type)
    //       });
    //     }
    //   }
    // })    
    that.getBussinessType();
    that.getDistanceList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    that.setData({
      loadShow: false
    })
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    var Type = that.data.isActive;  
    _PAGE = 1 
    that.getData(Type);     
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var hasMore = that.data.hasMore;
    var Type = that.data.isActive;        
    if(!hasMore){
      return false;
    }
    _PAGE++;
    that.setData({
      loading: true
    })
    that.getData(Type);
  },

  // 获取当前位置
  getLocation: function(successfun){
    var that = this;
    wx.getLocation({
      // type: 'wgs84',
      type: 'gcj02',
      success: function(res){
        latitude = res.latitude;
        longitude = res.longitude;
        that.setData({
          isLoacation: true,
          showFlag: false          
        });
        app.updateLatlng(res.latitude,res.longitude);
        successfun();
      },
      fail: function(err){        
        that.setData({
          isLoacation: false,
          showFlag: true     
        })
      }
    })

    
  },
  // 再次获取位置
  handler: function (e) {
    var that =this;
    that.getData(Type)
    console.log(e);
    // if (e.detail.authSetting["scope.userLocation"]) {
    //   //如果打开了地理位置，就会为true
    //   this.setData({
    //     isLoacation: true,
    //     showFlag: false
    //   });
    //   var Type = that.data.isActive;  
    //   console.log('二次授权后'); 
    //   that.getLocation(function () {
    //     that.getData(Type)
    //   });
         
      

    // }
  },
  // 获取订单类型列表
  getBussinessType: function(){
    var that = this;
    app.ajax({
      url:'Common/Common/getBussinessType',
      data:{},
      success:function(res){
        if(res.data.code == 1000){
          that.setData({
            screenTypes: res.data.data,
          })
        }else{
          // 没有数据
        }
      }
    })
  },
  // 获取距离列表
  getDistanceList: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getServiceConfig',
      data: {
        key: 'distance'
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            distanceList: res.data.data
          })
        } else {
          // 没有数据
        }
      }
    })
  },
  // 获取数据,dataType：1 获取大厅订单列表，2 获取指派订单列表
  getData: function(dataType){
    console.log(66666);
    var that = this;
    // if (!that.data.isLoacation && that.data.showFlag){
    //   app.showToast('请打开位置授权');
    //   return;
    // }
    var URL;
    if(dataType==1){
      URL = 'Engineer/Order/getHallOrderList';
    }else if(dataType == 2){
      URL = 'Engineer/Order/getAssignOrderList'
    }
    app.ajax({
      url: URL,
      load: load,
      msg: "数据加载中...",
      data: {
        business_id: that.data.selectTypeid,
        order: time,
        distance: distance,
        distance_range: that.data.selectDistance,
        lat: latitude,
        lng: longitude,
        searchKey: that.data.searchKey,
        page: _PAGE,
        pagesize: _PAGESIZE
      },
      success: function (res) {
        console.log(res);
        wx.stopPullDownRefresh();
        if(res.data.code == 1000){
          console.log(res.data.data);
          if(_PAGE == 1){
            that.setData({
              orderData: res.data.data,
              empty: false,              
            })
          }else{
            that.setData({
              orderData: that.data.orderData.concat(res.data.data),
              empty: false    
            });
          }
          // 是否加载更多
          var hasMore = true;
          if (res.data.data.length < _PAGESIZE) {
            hasMore = false;
          }
          load = false;
          that.setData({
            hasMore: hasMore,
            loading: false
          });
        }else{
          if (_PAGE == 1) {
            that.setData({
              hasMore: false,
              loading: false,
              empty: true
            })
          } else {
            that.setData({
              hasMore: false,
              loading: false,
              empty: false
            })
          }
        } 
        that.setData({
          loadShow: true
        })       
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  // 切换
  changeActive: function (e) {
    var that = this;
    var Type = e.currentTarget.dataset.type;
    that.setData({
      isActive: e.currentTarget.dataset.type,
      selectTypeid: [],
      selectDistance: '',
      selectType: '',
      screenShow: false,
      isMaskShow: false,
      isOrderSureShow: false,
      isSortTime: 0,
      isSortDis: 0,
      orderData:[],
      loadShow: false,
    });
    time = '';
    workid = '';
    load = true;
    _PAGE=1;
    this.getData(Type);
  },
  // 订单类型模块显、隐
  chooseType: function(){
    var that = this;
    if (that.data.screenShow == false){
      that.setData({
        screenShow1: false,
        move1: 0,
        screenShow: true,
        isMaskShow: true,
        move: 0
      })
    }else{
      that.setData({
        move: 1,
      })
      setTimeout(function(){
        that.setData({
          screenShow: false,
          isMaskShow: false,
        })
      },500)
    }
  },
  // 筛选模块显、隐
  chooseType1: function () {
    var that = this;
    if (that.data.screenShow1 == false) {
      that.setData({
        screenShow: false,
        move: 0,
        screenShow1: true,
        isMaskShow: true,
        move1: 0
      })
    } else {
      that.setData({
        move1: 1,
      })
      setTimeout(function () {
        that.setData({
          screenShow1: false,
          isMaskShow: false,
        })
      }, 500)
    }
  },
  // 关闭弹窗
  closeMask(){
    var that = this;
    that.setData({
      move: 1,
      move1: 1,
    })
    setTimeout(function () {
      that.setData({
        screenShow: false,
        screenShow1: false,
        isMaskShow: false,
      })
    }, 500)
  },

  //选择优惠活动分类
  ordertypeChoose(e) {
    var that = this;
    var obj = that.data.selectTypeid;
    var id = e.currentTarget.dataset.id;
    if (that.data.selectTypeid.indexOf(id) < 0) {
      obj.push(id);
    } else {
      obj.splice(that.data.selectTypeid.indexOf(id), 1)
    }
    console.log(obj);
    that.setData({
      selectTypeid: obj
    })
  },
  //选择距离分类
  distanceChoose(e) {
    var that = this;
    that.setData({
      selectDistance: e.currentTarget.dataset.id
    })
  },
  //确定选择的活动和距离
  sureChoose() {
    var that = this;
    that.setData({
      orderData: [],
    })
    that.closeMask();
    _PAGE = 1;
    that.getData(that.data.isActive);
  },
  //重置
  reset() {
    var that = this;
    that.setData({
      orderData: [],
      selectTypeid: [],
      selectDistance: '',
      selectType: '',
    })
    _PAGE = 1;
    that.getData(that.data.isActive);
  },

  // 点击订单类型
  typeClick:function(e){
    var typeindex = e.currentTarget.dataset.typeindex;
    var that = this;
    var screenTypes = that.data.screenTypes;
    var Type = that.data.isActive; 
    var selectTypeid = [];
    selectTypeid.push(screenTypes[typeindex].business_type_id);
    _PAGE=1;
    that.setData({
      selectType: screenTypes[typeindex].name,
      selectTypeid: selectTypeid,
      screenShow: false,
      isMaskShow: false,
      loadShow: false, 
    }); 
    load = true;
    that.getData(Type);    
  },
  // 抢单
  takeOrderRobbing: function(e){ 
    var that = this;
//    app.saveFormId(e.detail.formId);
    that.setData({
      isOrderSureShow: true,
    })
    workid = e.currentTarget.dataset.workid;
  },
  // 接单
  takeOrderReceipt: function (e) {
    var that =this;
   // app.saveFormId(e.detail.formId);
    that.setData({
      isOrderSureShow: true,
    })
    workid = e.currentTarget.dataset.workid;
    
  },
  // 取消接单
  orderCancel: function(){
    this.setData({
      isOrderSureShow: false,
    })
    workid = '';
  },
  // 确认接单
  orderSure: function(e){
    var that = this;
    var Type = that.data.isActive;
    //app.saveFormId(e.detail.formId);
    var URL;
    if(that.data.isActive==1){
      URL = 'Engineer/Order/grabOrder';
    } else if (that.data.isActive == 2){
      URL = 'Engineer/Order/receiveOrder'
    }
    app.ajax({
      url: URL,
      data: { work_order_id: workid},
      success:function(res){
        if(res.data.code == 1000){
          app.showToast(res.data.message, "none", 2000, function () { });
          wx.setStorageSync('tabIndex', 0);
          timer = setTimeout(function(){
            wx.switchTab({
              url: '../../order/myorder/myorder',
            });
          },2000);

        }else{
          app.showToast(res.data.message, "none", 2000, function () { });  
          that.getData(Type);                
        }
      }
    });
    that.setData({
      isOrderSureShow: false
    })
  },
  // 按距离排序
  sortDis: function(){
    var that = this;
    var Type = that.data.isActive;
    if(that.data.isSortDis==0){
      that.setData({
        isSortDis: 2 ,
      })
      distance = 'ASC';
    }else if( that.data.isSortDis ==1){
      that.setData({
        isSortDis: 2,   
      })
      distance = 'ASC';
    } else if (that.data.isSortDis == 2) {
      that.setData({
        isSortDis: 1,
      })
      distance = 'DESC';
    }
    that.setData({
      loadShow: false ,
      isSortTime: 0,
    })
    time = '';
    load = true;
    _PAGE = 1;
    that.getData(Type);    

  },
  // 按时间排序
  sortTime:function(){
    var that = this;
    var Type = that.data.isActive;
    if (that.data.isSortTime == 0) {
      that.setData({
        isSortTime: 2,
      })
      time = 'ASC'
    } else if (that.data.isSortTime == 1) {
      that.setData({
        isSortTime: 2,
      })
      time = 'ASC'
    } else if (that.data.isSortTime == 2) {
      that.setData({
        isSortTime: 1,
      })
      time = 'DESC'
    }
    that.setData({
      loadShow: false,
      isSortDis: 0,
    })
    distance = '';
    load = true;
    _PAGE = 1;
    that.getData(Type);
  },
  // 阻止遮罩滚动
  myCatchTouch: function(){
    return;
  },
  // 查看流程大图
  viewPicture(e) {
    var url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  },
  // 输入搜索字段
  inputSearch: function (e) {
    var that = this;
    var searchKey = e.detail.value;
    that.setData({
      searchKey: searchKey
    });
  },
  //小键盘直接搜索
  searchOrder: function (e) {
    var that = this;
    var key = e.detail.value;
    // if (key == '' || key == null) {
    //   app.showToast("请输入搜索关键字", "none", 2000, function () { });
    //   return;
    // }
    that.setData({
      orderData: [],
      searchKey: key
    })
    _PAGE = 1;
    var Type = that.data.isActive;
    that.getData(Type);
  },
  //点击搜索图标搜索
  searchOrder2: function () {
    var that = this;
    var key = that.data.searchKey;
    // if (key == '' || key == null) {
    //   app.showToast("请输入搜索关键字", "none", 2000, function () { });
    //   return;
    // }
    that.setData({
      orderData: [],
    })
    _PAGE = 1;
    var Type = that.data.isActive;
    that.getData(Type);
  },
})